package io.renren.service.impl;

import io.renren.config.FileServerConfig;
import io.renren.constant.AppConstant;
import io.renren.dao.MediaFileDao;
import io.renren.entity.FileUploadInfo;
import io.renren.entity.MediaFile;
import io.renren.service.FileService;
import io.renren.util.DfsUtil;
import io.renren.vo.FileServerResponse;
import io.renren.vo.RespModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private MediaFileDao mediaFileDao;

    @Autowired
    private FileServerConfig fileServerConfig;

    @Override
    public FileUploadInfo uploadFile(MultipartFile file) {
        FileUploadInfo fileUploadInfo = new FileUploadInfo();
        FileServerResponse fileServerResponse ;
        try {
            fileServerResponse = DfsUtil.uploadFileByMultipartFile(file, fileServerConfig.getImageUploadUrl());
            String furl = fileServerResponse.getHttpUrl(); //TODO 暂时设置待新的文件上传工具类完成后需要修改此处
            MediaFile mediaFile = new MediaFile();
            mediaFile.setProcessStatus("0");
            mediaFile.setCreateTime(new Date());
            if (("jpg").equals(file.getContentType()) || ("png").equals(file.getContentType())) {
                mediaFile.setMediaType("1");
            } else {
                mediaFile.setMediaType("2");
            }
            mediaFile.setMediaUrl(furl);
            mediaFileDao.createMediaFile(mediaFile);
            long mediaID = mediaFile.getMediaId();
            fileUploadInfo.setMediaID(mediaID);
            fileUploadInfo.setUrl(furl);
            fileUploadInfo.setStatus(AppConstant.STATU_SUCCESS.getName());
            return fileUploadInfo;
        } catch (IOException e) {
            e.printStackTrace();
            fileUploadInfo.setStatus("Fail "+e.getMessage());
            return fileUploadInfo;
        }
    }
}
